// 豆瓣刮削功能JS

document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const searchInput = document.getElementById('search-keyword');
    const searchButton = document.getElementById('search-btn');
    const searchResultsContainer = document.getElementById('search-results');
    const resultsList = document.getElementById('results-list');
    const movieDetailSection = document.getElementById('movie-detail-section');
    const clearDetailBtn = document.getElementById('clear-detail-btn');
    const generateNfoBtn = document.getElementById('generate-nfo-btn');
    const nfoResultSection = document.getElementById('nfo-result-section');
    const downloadNfoBtn = document.getElementById('download-nfo-btn');
    const nfoFilePathElement = document.getElementById('nfo-file-path');

    // 全局变量存储当前选中的电影
    let currentMovie = null;
    // 存储当前下载的海报文件名，用于临时文件管理
    let currentPosterFilename = null;
    // 标记是否已经生成NFO文件（生成后应保留海报）
    let nfoGenerated = false;

    // 搜索按钮点击事件
    if (searchButton) {
        searchButton.addEventListener('click', function() {
            searchMovies();
        });
    }

    // 搜索输入框回车事件
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchMovies();
            }
        });
    }

    // 清除详情按钮事件
    if (clearDetailBtn) {
        clearDetailBtn.addEventListener('click', function() {
            if (movieDetailSection) {
                movieDetailSection.classList.add('hidden');
                currentMovie = null;
            }
            if (nfoResultSection) {
                nfoResultSection.classList.add('hidden');
            }
        });
    }

    // 生成NFO文件按钮事件
    if (generateNfoBtn) {
        generateNfoBtn.addEventListener('click', function() {
            if (currentMovie && currentMovie.url) {
                generateNfoFile(currentMovie.url);
            } else {
                window.showNotification('请先选择一部电影', 'error');
            }
        });
    }

    // 搜索电影函数
    function searchMovies() {
        const keyword = searchInput.value.trim();
        if (!keyword) {
            window.showNotification('请输入搜索关键词', 'error');
            return;
        }

        // 显示加载状态（如果有）
        showLoading(true);

        // 发送搜索请求到正确的API路径
        fetch(`/api/douban/search?q=${encodeURIComponent(keyword)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                showLoading(false);
                
                if (data.success && data.data && data.data.length > 0) {
                    // 显示搜索结果区域
                    if (searchResultsContainer) {
                        searchResultsContainer.classList.remove('hidden');
                    }
                    // 渲染搜索结果
                    renderSearchResults(data.data);
                } else {
                    // 无结果或请求失败
                    if (searchResultsContainer) {
                        searchResultsContainer.classList.remove('hidden');
                    }
                    if (resultsList) {
                        resultsList.innerHTML = '<div class="text-center p-6 text-gray-500">未找到相关电影</div>';
                    }
                }
            })
            .catch(error => {
                console.error('搜索电影失败:', error);
                showLoading(false);
                window.showNotification('搜索失败: ' + error.message, 'error');
            });
    }

    // 渲染搜索结果
    function renderSearchResults(results) {
        if (!resultsList) return;

        let html = '';
        results.forEach(movie => {
            html += `
                <div class="movie-result-item p-3 border border-gray-200 rounded-lg hover:bg-gray-50 hover:border-primary cursor-pointer transition-all" data-url="${movie.url}">
                    <div class="flex items-start">
                        ${movie.poster_url ? `
                        <div class="w-16 h-24 bg-gray-100 rounded overflow-hidden mr-4 flex-shrink-0">
                            <img src="${movie.poster_url}" alt="${movie.title}" class="w-full h-full object-cover">
                        </div>` : ''}
                        <div class="flex-grow">
                            <div class="flex items-center justify-between">
                                <h4 class="font-medium text-gray-800">${movie.title}</h4>
                                <span class="text-xs text-gray-500">${movie.year}</span>
                            </div>
                            <p class="text-sm text-gray-600 mt-1">${movie.info}</p>
                        </div>
                    </div>
                </div>
            `;
        });

        resultsList.innerHTML = html;

        // 为每个结果项添加点击事件
        const resultItems = document.querySelectorAll('.movie-result-item');
        resultItems.forEach(item => {
            item.addEventListener('click', function() {
                const movieUrl = this.getAttribute('data-url');
                if (movieUrl) {
                    getMovieDetail(movieUrl);
                }
            });
        });
    }

    // 获取电影详情
    function getMovieDetail(movieUrl) {
        showLoading(true);

        // 隐藏结果区域
        if (searchResultsContainer) {
            searchResultsContainer.classList.add('hidden');
        }
        // 隐藏之前的结果区域
        if (nfoResultSection) {
            nfoResultSection.classList.add('hidden');
        }
        
        // 删除之前的临时海报文件（如果存在）
        deleteTempPoster();

        // 发送获取详情请求到正确的API路径
        fetch(`/api/douban/detail?url=${encodeURIComponent(movieUrl)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                showLoading(false);
                
                if (data.success && data.data) {
                    // 存储当前电影信息
                    currentMovie = data.data;
                    // 渲染电影详情
                    renderMovieDetail(data.data);
                    // 显示详情区域
                    if (movieDetailSection) {
                        movieDetailSection.classList.remove('hidden');
                        // 滚动到详情区域
                        movieDetailSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                } else {
                    window.showNotification('获取电影详情失败', 'error');
                }
            })
            .catch(error => {
                console.error('获取电影详情失败:', error);
                showLoading(false);
                window.showNotification('获取电影详情失败: ' + error.message, 'error');
            });
    }

    // 渲染电影详情
    function renderMovieDetail(movie) {
        console.log('收到的电影详情数据:', movie);
        
        // 检查元素是否存在，避免null引用错误
        const checkElementExists = (id) => {
            const element = document.getElementById(id);
            return element;
        };
        
        // 更新各种电影信息元素
        const posterElement = checkElementExists('movie-poster');
        if (posterElement) {
            if (movie.poster_url) {
                // 尝试通过后端API下载海报
                const movieId = movie.douban_id || movie.url.split('/').filter(Boolean).pop();
                const title = movie.title || '电影';
                
                // 构建后端下载海报的API URL
                // 对movieId也进行安全处理，去除可能导致问题的特殊字符
                const safeMovieId = movieId.replace(/[\/:*?"<>|]/g, '');
                const downloadUrl = '/api/douban/download-poster?url=' + encodeURIComponent(movie.poster_url) + '&id=' + encodeURIComponent(safeMovieId) + '&title=' + encodeURIComponent(title);
                
                // 发送请求到后端下载海报
                fetch(downloadUrl)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.local_path && data.filename) {
                            // 保存文件名用于后续删除
                            currentPosterFilename = data.filename;
                            // 重置NFO生成标记
                            nfoGenerated = false;
                            
                            // 构建本地访问路径
                            // 确保正确使用data/images路由，而不是直接拼接路径
                            const filename = data.local_path.split('/').pop();
                            const localImageUrl = '/data/images/' + encodeURIComponent(filename);
                            posterElement.src = localImageUrl;
                            posterElement.style.display = 'block';
                        } else {
                            // 失败时使用占位图
                            posterElement.src = '/static/images/placeholder.svg';
                            posterElement.style.display = 'block';
                            // 重置海报文件信息
                            currentPosterFilename = null;
                        }
                    })
                    .catch(error => {
                        // 出错时使用占位图
                        posterElement.src = '/static/images/placeholder.svg';
                        posterElement.style.display = 'block';
                    });
            } else {
                posterElement.style.display = 'none';
            }
        }
        
        const titleElement = checkElementExists('movie-title');
        if (titleElement) {
            titleElement.textContent = movie.title || '未知';
        }
        
        const originalTitleElement = checkElementExists('movie-original-title');
        if (originalTitleElement) {
            originalTitleElement.textContent = movie.original_title || movie.originaltitle || '';
        }
        
        const ratingElement = checkElementExists('movie-rating');
        if (ratingElement) {
            ratingElement.textContent = movie.rating || '暂无评分';
        }
        
        const ratingCountElement = checkElementExists('movie-rating-count');
        if (ratingCountElement) {
            ratingCountElement.textContent = `(${movie.rating_count || 0}人评价)`;
        }
        
        const yearElement = checkElementExists('movie-year');
        if (yearElement) {
            // 处理年份字段，确保能正确显示
            const yearValue = movie.year || 
                             (movie.release_date ? movie.release_date.substring(0, 4) : '未知');
            yearElement.textContent = yearValue;
        }
        
        const genresElement = checkElementExists('movie-genres');
        if (genresElement) {
            // 处理类型字段，支持多种可能的字段名
            const genresValue = Array.isArray(movie.genres) && movie.genres.length > 0 ? 
                               movie.genres.join(' / ') : 
                               (Array.isArray(movie.category) && movie.category.length > 0 ? 
                                movie.category.join(' / ') : '未知');
            genresElement.textContent = genresValue;
        }
        
        const durationElement = checkElementExists('movie-duration');
        if (durationElement) {
            // 处理时长字段，支持多种可能的字段名
            const durationValue = movie.duration || 
                                 (movie.runtime ? movie.runtime : '未知');
            durationElement.textContent = durationValue;
        }
        
        const summaryElement = checkElementExists('movie-summary');
        if (summaryElement) {
            // 处理简介字段，支持多种可能的字段名
            const summaryValue = movie.summary || 
                               (movie.introduction ? movie.introduction : '暂无简介');
            summaryElement.textContent = summaryValue;
        }
        
        const directorsElement = checkElementExists('movie-directors');
        if (directorsElement) {
            // 处理导演字段
            const directorsValue = Array.isArray(movie.directors) && movie.directors.length > 0 ? 
                              movie.directors.join(' / ') : '未知';
            directorsElement.textContent = directorsValue;
        }
        
        const writersElement = checkElementExists('movie-writers');
        if (writersElement) {
            // 处理编剧字段，从info字段中提取作为备选方案
            let writersValue = '未知';
            if (Array.isArray(movie.writers) && movie.writers.length > 0) {
                writersValue = movie.writers.join(' / ');
            } else if (movie.info && typeof movie.info === 'string') {
                // 尝试从info字段中提取编剧信息
                const writersMatch = movie.info.match(/编剧[:\s](.*?)(?:类型|制片国家|上映日期|)/);
                if (writersMatch && writersMatch[1]) {
                    writersValue = writersMatch[1].split('/').map(w => w.trim()).join(' / ');
                }
            }
            writersElement.textContent = writersValue;
        }
        
        const actorsElement = checkElementExists('movie-actors');
        if (actorsElement) {
            // 处理主演字段
            const actorsValue = Array.isArray(movie.actors) && movie.actors.length > 0 ? 
                           movie.actors.join(' / ') : '未知';
            actorsElement.textContent = actorsValue;
        }
    }

    // 删除临时海报文件
    function deleteTempPoster() {
        if (currentPosterFilename && !nfoGenerated) {
            fetch('/api/douban/delete-poster', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ filename: currentPosterFilename })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (!data.success) {
                    // 静默处理错误，不显示控制台输出
                }
            })
            .catch(error => {
                // 静默处理错误，不显示控制台输出
            })
            .finally(() => {
                // 无论删除成功与否，都重置文件名
                currentPosterFilename = null;
            });
        }
    }

    // 生成NFO文件
    function generateNfoFile(movieUrl) {
        showLoading(true);

        // 发送生成NFO请求到正确的API路径
        fetch('/api/douban/generate-nfo', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ url: movieUrl })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                showLoading(false);
                
                if (data.success && data.data) {
                    // 标记NFO已生成，保留海报文件
                    nfoGenerated = true;
                    
                    // 更新当前电影信息
                    currentMovie.nfo_path = data.data.nfo_path;
                    currentMovie.poster_path = data.data.poster_path;
                    
                    // 显示生成结果区域
                    if (nfoResultSection) {
                        nfoResultSection.classList.remove('hidden');
                        // 滚动到结果区域
                        nfoResultSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                    
                    // 更新文件路径显示
                    let resultMessage = '';
                    if (data.data.nfo_path) {
                        resultMessage += `NFO文件已保存至: ${data.data.nfo_path}<br/>`;
                    }
                    if (data.data.poster_path) {
                        resultMessage += `海报图片已保存至: ${data.data.poster_path}`;
                    }
                    
                    if (nfoFilePathElement) {
                        nfoFilePathElement.innerHTML = resultMessage;
                    }
                    
                    // 显示成功通知
                    window.showNotification('NFO文件和海报生成成功', 'success');
                } else {
                    window.showNotification('生成NFO文件失败: ' + (data.message || '未知错误'), 'error');
                }
            })
            .catch(error => {
                showLoading(false);
                window.showNotification('生成NFO文件失败: ' + error.message, 'error');
            });
    }

    // 显示/隐藏加载状态（简单实现，实际项目中可以添加加载动画）
    function showLoading(show) {
        // 可以在这里添加加载状态的显示逻辑
    }

    // 初始化页面时隐藏不需要显示的区域
    if (movieDetailSection) {
        movieDetailSection.classList.add('hidden');
    }
    if (nfoResultSection) {
        nfoResultSection.classList.add('hidden');
    }
    if (searchResultsContainer) {
        searchResultsContainer.classList.add('hidden');
    }
    
    // 在页面卸载时删除临时海报文件（如果没有生成NFO）
    window.addEventListener('beforeunload', function() {
        deleteTempPoster();
    });
    
    // 监听搜索按钮点击事件，在搜索新电影前删除临时海报
    if (searchButton) {
        searchButton.addEventListener('click', function() {
            deleteTempPoster();
        });
    }
});